//
//  SQLiteManager.m
//  SQL(OC)
//
//  Created by 姚英 on 16/6/21.
//  Copyright © 2016年 yy. All rights reserved.
//

#import "SQLiteManager.h"
//#import <sqlite3.h>
#import <FMDB.h>

//static SQLiteManager *_instance;

@interface SQLiteManager ()

///
@property(nonatomic, strong) FMDatabase *db;

@end

@implementation SQLiteManager

#pragma mark - 单例

static id  _instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}
+(instancetype)shareSQLiteManager
{
    return [[self alloc]init];
}

//-(id)copyWithZone:(NSZone *)zone
//{
//    return _instance;
//}
//
//-(id)mutableCopyWithZone:(NSZone *)zone
//{
//    return _instance;
//}


#pragma mark - 数据库操作

/// open
- (BOOL)openDB:(NSString *)dbPath{
    
    _db = [FMDatabase databaseWithPath:dbPath];
    return _db.open;
}

/// exec
- (BOOL)exec:(NSString *)sqlStr{
    return [_db executeUpdate:sqlStr];
}

/// transaction
- (void)beginTransation{
    [_db beginTransaction];
}

- (void)commitTransation{
    [_db commit];
}

- (void)rollbackTransation{
    [_db rollback];
}

- (NSArray *)queryData:(NSString *)querySQLStr{
    FMResultSet *result = [_db executeQuery:querySQLStr withArgumentsInArray:nil];
    
    NSInteger count = result.columnCount;
    
    NSMutableArray *tempArray = [NSMutableArray array];
    
    while (result.next) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        for (int i =0; i < count; i++) {
            NSString *key = [result columnNameForIndex:i];
            NSString *value = [result stringForColumnIndex:i];
            
            dict[key] = value;
        }
        [tempArray addObject:dict];
    }
    return tempArray;
}

//"insert into bulktest2 (y) values ('YYY');"

-(BOOL)executeData:(NSString *)SQLStr{
    return [_db executeStatements:SQLStr];
}

//// 查询是否唯一存在该城市
//- (BOOL)isExistCity:(NSString *)querySQLStr{
//    
//    
//    FMResultSet *result = [_db executeQuery:querySQLStr withArgumentsInArray:nil];
//    
//    NSInteger count = result.columnCount;
//    
//    if (count == 1) {
//        return 1;
//    }
//    return 0;
//}

@end
